package com.yanjue.controller;

import com.yanjue.common.entity.Book;
import com.yanjue.common.redisKey.RedisBookKey;
import com.yanjue.common.redisKey.RedisExpire;
import com.yanjue.common.redisKey.RedisService;
import com.yanjue.common.util.Result;
import com.yanjue.common.util.ResultUtil;
import com.yanjue.mapper.BookMapper;
import com.yanjue.service.BookService;
import com.yanjue.vo.BookVO;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 图书接口
 */
@Api(description = "图书查询接口")
@RestController
@RequestMapping("book")
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private RedisService redisService;

    @ApiOperation(value = "查询图书基本信息" , httpMethod = "GET")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "query", name = "bookId", value = "图书ID", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "", response = Book.class)})
    @GetMapping("/getBookById")
    public Result getBookById(String bookId){
        //1.获取缓存
        String key = RedisBookKey.getBookKey(bookId);
        Book book = this.redisService.getCache(key, Book.class);
        if (null == book){
            //2.缓存不在查数据库
            book = bookMapper.selectById(bookId);
            if (null != book){
                //数据库不为空，写入·缓存
                redisService.setExpireCache(key,book, RedisExpire.DAY);
            }
        }
        return ResultUtil.success(book);
    }






    @ApiOperation(value = "获取图书详情" , httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "bookId", value = "图书ID", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "", response = Book.class)})
    @GetMapping("/details")
    public Result<BookVO> getBookDetails(String bookId){
        return bookService.getBookDetails(bookId);
    }
}